<template>
	<div class="import-confirmation">
		<div class="confirmation-header">
			<h3>导入确认</h3>
			<div class="confirmation-info">
				<el-tag type="info">总行数: {{ excelData.length }}</el-tag>
			</div>
		</div>

		<div class="confirmation-details">
			<el-descriptions :column="2" border>
				<el-descriptions-item label="数据行数">{{ excelData.length }}</el-descriptions-item>
				<el-descriptions-item label="数据列数">{{ headers.length }}</el-descriptions-item>
				<el-descriptions-item label="表头字段" :span="2">{{
					headers.join(', ')
				}}</el-descriptions-item>
			</el-descriptions>
		</div>

		<div class="import-options">
			<h4>导入选项</h4>
			<el-form :model="importOptions" label-width="180px">
				<el-form-item label="导入类型">
					<el-radio-group v-model="importOptions.importType">
						<el-radio label="new">新增记录</el-radio>
						<el-radio label="update">更新已有记录</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="学科">
					<el-select v-model="importOptions.subjectId" placeholder="请选择学科" filterable>
						<el-option
							v-for="item in subjectOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>

				<el-form-item label="班级">
					<el-select v-model="importOptions.classId" placeholder="请选择班级" filterable>
						<el-option
							v-for="item in classOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
			</el-form>
		</div>

		<div class="confirmation-warning">
			<el-alert
				title="确认导入将直接影响数据库中的数据，请确认数据无误后再操作。"
				type="warning"
				:closable="false"
				show-icon
			/>
		</div>

		<div class="action-buttons">
			<el-button @click="goBack">返回上一步</el-button>
			<el-button
				type="primary"
				@click="confirmImport"
				:loading="importing"
				:disabled="!isFormValid"
			>
				确认导入
			</el-button>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadFileService } from '../../../api/file'

const props = defineProps<{
	excelData: any[]
	headers: string[]
}>()

const emit = defineEmits(['import-success', 'import-failed', 'go-back'])

// 导入状态
const importing = ref(false)

// 表单选项
const importOptions = reactive({
	importType: 'new', // 导入类型: new-新增, update-更新, replace-替换
	conflictStrategy: 'skip', // 冲突处理: skip-跳过, override-覆盖, merge-合并
	subjectId: '', // 学科ID
	classId: '', // 班级ID
	examType: '', // 考试类型
	remark: '' // 备注
})

// 学科选项（示例数据，实际应该从API获取）
const subjectOptions = [
	{ value: '1', label: '数学' },
	{ value: '2', label: '语文' },
	{ value: '3', label: '英语' },
	{ value: '4', label: '物理' },
	{ value: '5', label: '化学' },
	{ value: '6', label: '生物' }
]

// 班级选项（示例数据，实际应该从API获取）
const classOptions = ref([
	{ value: '1', label: '高一(1)班' },
	{ value: '2', label: '高一(2)班' },
	{ value: '3', label: '高二(1)班' },
	{ value: '4', label: '高二(2)班' },
	{ value: '5', label: '高三(1)班' },
	{ value: '6', label: '高三(2)班' }
])

// 表单验证
const isFormValid = computed(() => {
	return importOptions.subjectId && importOptions.classId && importOptions.examType
})

// 返回上一步
const goBack = () => {
	emit('go-back')
}

// 确认导入
const confirmImport = async () => {
	if (!isFormValid.value) {
		ElMessage.warning('请填写完整的导入选项')
		return
	}

	try {
		// 弹出最终确认框
		await ElMessageBox.confirm('确定要导入这些数据吗？此操作将直接影响数据库。', '导入确认', {
			confirmButtonText: '确认导入',
			cancelButtonText: '取消',
			type: 'warning'
		})

		importing.value = true

		// 构建导入数据
		const importData = {
			data: props.excelData,
			options: importOptions
		}

		// 这里可以调用API上传数据
		// 1. 转为FormData
		const formData = new FormData()
		const blob = new Blob([JSON.stringify(importData)], { type: 'application/json' })
		formData.append('file', blob, 'scores.json')
		formData.append('type', 'score')
		formData.append('options', JSON.stringify(importOptions))

		// 2. 调用上传API
		const response = await uploadFileService(formData)

		// 3. 处理响应
		if (response.data && response.data.code === 1) {
			ElMessage.success('成绩导入成功')
			emit('import-success')
		} else {
			throw new Error(response.data?.msg || '导入失败')
		}
	} catch (error: any) {
		if (error === 'cancel') {
			// 用户取消操作
			return
		}

		console.error('导入失败:', error)
		const errorMessage = error.message || '导入过程中发生错误'
		emit('import-failed', errorMessage)
		ElMessage.error(errorMessage)
	} finally {
		importing.value = false
	}
}
</script>

<style lang="scss" scoped>
.import-confirmation {
	width: 100%;

	.confirmation-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;

		h3 {
			margin: 0;
			color: var(--el-text-color-primary);
		}

		.confirmation-info {
			display: flex;
			gap: 10px;
		}
	}

	.confirmation-details {
		margin-bottom: 20px;
	}

	.import-options {
		margin-bottom: 20px;

		h4 {
			margin-top: 0;
			margin-bottom: 15px;
			color: var(--el-text-color-primary);
			font-weight: normal;
		}
	}

	.confirmation-warning {
		margin-bottom: 20px;
	}

	.action-buttons {
		display: flex;
		justify-content: center;
		gap: 15px;
	}
}
</style>
